package com.jianguozh.difs.support.api.framework;

import cn.hutool.core.io.IoUtil;
import com.jianguozh.difs.common.bean.R;
import com.jianguozh.difs.framework.base.BaseController;
import com.jianguozh.difs.framework.utils.ServletUtils;
import com.jianguozh.difs.support.service.base.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件控制器
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/7/12 16:19
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController extends BaseController {

    @Resource
    private IFileService fileService;

    /**
     * 文件上传
     *
     * @param file
     * @param path
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public R<String> uploadFile(@RequestParam("file") MultipartFile file,
                                @RequestParam(value = "path", required = false) String path) throws Exception {
        return success(fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream())));
    }

    /**
     * 文件下载
     *
     * @param response
     * @param path
     * @throws Exception
     */
    @GetMapping("/download/{path}")
    public void getFileContent(HttpServletResponse response,
                               @PathVariable("path") String path) throws Exception {
        byte[] content = fileService.getFileContent(path);
        if (content == null) {
            log.warn("[getFileContent][configId({}) path({}) 文件不存在]", path);
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        ServletUtils.writeAttachment(response, path, content);
    }

}
